package com.ly.honor.exception;

/**
 * @Author LiYang
 * @Date 2022/11/17 11:19
 * @Version 1.0
 */

import com.ly.honor.util.Result;
import com.ly.honor.util.ResultEnum;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

@ControllerAdvice  //AOP
public class GlobalExceptionHandler {

    private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

    // 自定义异常处理HonorException
    @ExceptionHandler(HonorException.class)
    @ResponseBody
    public Result error(HonorException e){
        e.printStackTrace();
        return Result.fail().message(e.getMsg()).code(e.getCode());
    }
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result throwCustomException(MethodArgumentNotValidException methodArgumentNotValidException){

        var errors = methodArgumentNotValidException.getBindingResult().getAllErrors();
        logger.error(errors.get(0).getDefaultMessage());
        if(errors.size() != 0){
            return Result.fail().message(errors.get(0).getDefaultMessage());
        }
        return null;
    }

    // 全局异常处理
    @ExceptionHandler
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail(ResultEnum.GLOBAL_EXCEPTION);
    }



}
